import { LogHelper } from "../../utils/logHelper";

class HarvestSourcTask implements ICreepTask {
  public run(creep: Creep): void {
    // harvesterSourc 负责采集房间内的 Sourc,每个harvesterSourc需要均匀分配到每个Sourc资源上采集

    let source = null;
    // 是否分配了采集资源的目标
    if(!creep.memory.source){
      const sources = creep.room.find(FIND_SOURCES);
      const target = sources.sort((a:Source,b:Source)=>{
        const creepCountA = creep.room.find(FIND_MY_CREEPS)
          .filter((item:Creep)=>{
            if(item.memory.role === creep.memory.role){
              if(item.memory.source?.id === a.id)
              {
                return item;
              }
            }
          }).length;
        
        const creepCountB = creep.room.find(FIND_MY_CREEPS)
          .filter((item:Creep)=>{
            if(item.memory.role === creep.memory.role){
              if(item.memory.source?.id === b.id)
              {
                return item;
              }
            }
          }).length;
        
        return creepCountA - creepCountB;
      })[0];
      creep.memory.source = { id:target.id,pos:target.pos };
    }
    else{
      source = Game.getObjectById(creep.memory.source.id) as Source;
    }

    if(source){
      const result = creep.harvest(source);
      if (result === ERR_NOT_IN_RANGE) {
        creep.go(source.pos);
      }
    }

    // 采集满了,丢在脚下
    if(creep.store.getFreeCapacity(RESOURCE_ENERGY) === 0){
      if (creep.store.getUsedCapacity() > 0) {
        creep.drop(RESOURCE_ENERGY);
      }
    }

    // 如果为外矿的采集 自动申请
    if(creep.ticksToLive && creep.ticksToLive <= 30){
      if(creep.memory.bornRoom != creep.memory.source.pos.roomName && !creep.memory.spawnApplyFor){
        const room = Game.rooms[creep.memory.bornRoom];
        const role = 'harvesterSourc';
        const body = room.calculateCreepBody({
          [WORK]: 0.6,
          [MOVE]: 0.3,
          [CARRY]: 0.1,
        },1000);
        room.spawnQueueAdd(role,body,{ role, bornRoom:room.name, source: { id:creep.memory.source.id,pos:creep.memory.source.pos }});
        creep.memory.spawnApplyFor = true;
        LogHelper.log(`外矿采集 Creep [${creep.name}] 申请孵化 ${role}`);
      }
    }

  }
}

export { HarvestSourcTask };